package cn.yunyichina.provider.pay.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.iface.entity.base.EventVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.pay.constant.MethodRouter;
import cn.yunyichina.provider.pay.dao.OrderCheckedExceptionDao;
import cn.yunyichina.provider.pay.dao.PaymentCheckSourceFileDao;
import cn.yunyichina.provider.pay.dao.PaymentJournalDao;
import cn.yunyichina.provider.pay.dao.PaymentSettingDao;
import cn.yunyichina.provider.pay.entity.OrderCheckedException;
import cn.yunyichina.provider.pay.entity.PaymentCheckSourceFile;
import cn.yunyichina.provider.pay.entity.PaymentJournal;
import cn.yunyichina.provider.pay.entity.PaymentSetting;
import cn.yunyichina.provider.pay.entity.SettlementSetting;
import cn.yunyichina.provider.pay.service.AlipayPaymentService;
import cn.yunyichina.provider.pay.service.CheckPaymentService;
import cn.yunyichina.provider.pay.service.HisPayfinanceService;
import cn.yunyichina.provider.pay.service.PaymentServiceImpl;
import cn.yunyichina.provider.pay.service.WechatPaymentService;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 对账主流程——第三方账单与我方交易流水账单对账
 * Created by JoeZ on 2016/10/20.
 */
@Service
public class CheckPaymentServiceImpl implements CheckPaymentService {

    private static Logger logger = LoggerFactory.getLogger(AlipayPaymentServiceImpl.class);

    @Resource
    private AlipayPaymentService alipay;

    @Resource
    private WechatPaymentService wechat;

    @Autowired
    private PaymentSettingDao paymentSettingDao;

    @Autowired
    private PaymentCheckSourceFileDao paymentCheckSourceFileDao;

    @Autowired
    private PaymentJournalDao paymentJournalDao;

    @Resource
    private HisPayfinanceService hisPayfinanceService;

    @Resource
    private ThirdFinanceServiceImpl thirdPartyfinanceService;

    @Resource
    private PaymentServiceImpl paymentService;

    @Resource
    private OrderCheckedExceptionDao orderCheckedExceptionDao;

    @Resource
    private FinanceServiceImpl financeService;

    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    SimpleDateFormat YYYYMMDDHHMISS14 = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 根据指定条件进行对账工具
     * @interfaceName:yyt.pay.check.payment.platform
     * @param datas
     */
    public Response platformCheckPayment(String datas) {

        Response response = null;
        Map<String, String> maps = JsonUtils.parseObject(datas, Map.class);
        String beginDate = maps.get("beginDate");
        String endDate = maps.get("endDate");
        String orgCode = maps.get("orgCode");

        response = new Response();
        response.setResultCodeAndMessage(Response.FAILURE_CODE , "该高级接口暂时无法使用,对您带来的不便,我们深感抱歉");

//        response = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_ORG_BY_CODE, JsonUtils.toJsonString(orgCode));
//        if("0".equals(response.getResultCode())){
//            Org org = JsonUtils.parseObject(response.getResult(), Org.class);
//
//            //清理第三方数据
//            maps = new HashMap<String, String>();
//            maps.put("beginPayTime" , beginDate);
//            maps.put("endPayTime" , endDate);
//            maps.put("clearFlag" , "1");
//            maps.put("orgId" , org.getId());
//            response = clearCheckPaymentForDatas(JSON.toJSONString(maps));
//            if(!"0".equals(response.getResultCode())){
//                return response;
//            }
//
//            //清理his数据
//            List<Date> betweenDates = new ArrayList<Date>();
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                betweenDates = cn.yunyichina.provider.pay.utils.DateUtils.getDatesBetweenTwoDate(dateFormat.parse(beginDate), dateFormat.parse(endDate));
//                for (Date payDate : betweenDates) {
//                    maps = new HashMap<String, String>();
//                    maps.put("orgId" , org.getId());
//                    maps.put("payTime" , dateFormat.format(payDate));
//                    maps.put("isClearHis" , "1");
//                    response = hisPayfinanceService.resetHisPayfinanceInfo(JSON.toJSONString(maps));
//                    if(!"0".equals(response.getResultCode())){
//                        return response;
//                    }
//                }
//
//            } catch (Exception e) {
//                logger.info("[CheckPaymentServiceImpl.platformCheckPayment.resetHisPayfinanceInfo]" ,e);
//            }
//
//            //获取paymentSetting配置
//            PaymentSetting paymentSetting = new PaymentSetting();
//            paymentSetting.setOrgId(org.getId());
//            paymentSetting.setEnableFlag((short) 1);
//            paymentSetting.setCheckFlag((short) 1);
//            List<PaymentSetting> paymentSettings = paymentSettingDao.select(paymentSetting);
//            List<String> ars = new ArrayList<String>();
//            if(paymentSettings.size() < 1){
//                maps = new HashMap<String, String>();
//                maps.put("org_id" ,org.getId());
//                ResponseObject resp = paymentService.queryPaymentSettingBySettlementSetting(JSONUtils.toJSONString(maps));
//                if("0".equals(resp.getResultCode())){
//                    List<SettlementSetting> settings = (List<SettlementSetting>) resp.getResultObject();
//                    for (SettlementSetting settingVo : settings) {
//                        ResCommon<PaymentSettingResponse> resCommon = PayService.getPayClient().queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(settingVo.getPlatformOrgAppCode(), settingVo.getDevOrgCode(), settingVo.getPayMode());
//                        if("0".equals(resCommon.getResultCode())){
//                            PaymentSettingResponse setting = resCommon.getResult();
//                            PaymentSetting paySetting = new PaymentSetting();
//                            BeanUtils.copyProperties(setting , paySetting);
//                            if(!ars.contains(paySetting.getPayAppId())){
//                                paymentSettings.add(paySetting);
//                                ars.add(paySetting.getPayAppId());
//                            }
//                        }
//                    }
//                }
//            }
//
//            List<FutureTask<Object>> futureList = new ArrayList<FutureTask<Object>>();
//            for (PaymentSetting setting : paymentSettings) {
//                if(setting.getCheckFlag() == 1 && setting.getEnableFlag() == 1){
//                    for (Date payDate : betweenDates) {
//                        FutureTask payTask = new FutureTask(new PaymentCheckRunnable(setting, dateFormat.format(payDate), org.getId(), org.getOrgName()));
//                        FutureTask hisTask = new FutureTask(new HisPayfinanceRunnable(org.getId(), org.getOrgName(), "2".equals(org.getOrgType()) ? org.getOrgCode() : "", org.getOrgCode(), dateFormat.format(payDate), null, "0"));
//                        futureList.add(payTask);
//                        futureList.add(hisTask);
//                    }
//                }
//            }
//
//
//            if(futureList.size() > 0){
//                //线程执行
//                for (FutureTask<Object> task : futureList) {
//                    threadPool.submit(task);
//                }
//
//                List<Date> failDates = new ArrayList<Date>();
//                for (FutureTask<Object> task : futureList) {
//                    try {
//                        Response futureRes = (Response) task.get();
//                        if (!"0".equals(futureRes.getResultCode())) {
//                            String errorDate = futureRes.getResult();
//                            logger.info("Error org dates: 日期——" + errorDate +"——"+ futureRes.getResultMessage());
//                            response.setResultCodeAndMessage(futureRes.getResultCode() , futureRes.getResultMessage());
//
//                            if(response.FAILURE_CODE.equals(futureRes.getResultCode())){
//                                return response;
//                            }else{
//                                for (int i = 0; i < betweenDates.size(); i++) {
//                                    if(errorDate.equals(dateFormat.format(betweenDates.get(i))) && !failDates.contains(betweenDates.get(i))){
//                                        failDates.add(betweenDates.get(i));
//                                    }
//                                }
//                            }
//                        }
//                    } catch (Exception e) {
//                        logger.error("[CheckPaymentServiceImpl.doExecute.jobs.futureTaskList]", e);
//                    }
//                }
//
//                //删除执行失败的日期
//                if(failDates.size() > 0){
//                    for (Date date : failDates) {
//                        betweenDates.remove(date);
//                    }
//                }
//
//                threadPool.shutdown();
//
//                //查询该组织下规则配置sys_rule,确定是否对账
//                maps = new HashMap<String, String>();
//                maps.put("attribute_name" , Config.RULE_ATTRIBUTE_NAME_FOR_RULE_ATTRIBUTE_NAME);
//                maps.put("org_code" , orgCode);
//                response = BaseService.callHumpFromInternal(MethodRouter.FIND_SYS_RULE_ATTRIBUTE, JSON.toJSONString(maps));
//                if(StringUtils.isBlank(response.getResult())){
//                    response.setResultCodeAndMessage("5003" , org.getOrgName() + "规则配置sys_rule,不支持对账！");
//                    return response;
//                }
//
//
//                //执行第三方对账
//                int size = 0;
//                try {
//                    for (Date payDate : betweenDates) {
//                        maps = new HashMap<String, String>();
//                        maps.put("orgId", org.getId());
//                        maps.put("date", dateFormat.format(payDate));
//                        size = thirdPartyfinanceService.checkingThirdfinance(JSON.toJSONString(maps));
//                        logger.info(">>" + org.getOrgName() + format.format(payDate) + "成功对账：" + size +" 笔！ ");
//                    }
//                } catch (Exception e) {
//                    logger.error("[CheckPaymentServiceImpl.doExecute.jobs.thirdPartyfinanceService.checkingThirdfinance] 第三方对账执行出错！" , e);
//                }
//
//
//                if(size > 0){
//                    //执行his对账
//                    try {
//                        for (Date payDate : betweenDates) {
//                            maps = new HashMap<String, String>();
//                            maps.put("orgId", org.getId());
//                            maps.put("payTime", dateFormat.format(payDate));
//                            hisPayfinanceService.checkHisPayFinancePlat(JSON.toJSONString(maps));
//                        }
//                    } catch (Exception e) {
//                        logger.error("[CheckPaymentServiceImpl.doExecute.jobs.thirdPartyfinanceService.checkingThirdfinance] His对账执行出错！" , e);
//                    }
//                }else{
//                    response.setResultCodeAndMessageAndResult("5003","执行第三方对账数据为0","");
//                }
//
//                response.setResultCodeAndMessageAndResult("0","对账执行完毕,已对日期" + betweenDates.toString(),"");
//            }else{
//                logger.info("futureList size is < 0 ~");
//            }
//        }
        return response;
    }


    /**
     * 根据指定医院进行对账
     *
     * @param datas
     */
    public Response platformCheckPaymentByHospital(String datas) {

    	JSONObject mapReturn = new JSONObject();
        Response response = new Response();
		boolean getDataFlag = true;
		boolean checkAccountFlag = true;
		
		Map<String, String> maps = JsonUtils.parseObject(datas, Map.class);
		String date = maps.get("checkDate");
		String payMode  = maps.get("payMode");
		String orgId = maps.get("orgId");
		String orgName = maps.get("orgName");
		String eType = maps.get("eType");   // 1:生产环境  2：测试环境
		date = DateUtils.getDateForType(date , 2);
		
		try {
			

			PaymentSetting paymentSetting = new PaymentSetting();
			paymentSetting.setOrgId(orgId);
			paymentSetting.setEnableFlag((short) 1);
			paymentSetting.setCheckFlag((short) 1);
			List<PaymentSetting> paymentSettings = paymentSettingDao.select(paymentSetting);
			ArrayList<String> errors = new ArrayList<>();
			maps.put("date" , date);
			maps.put("orgId" , orgId);
			maps.put("orgName" , orgName);
			maps.put("tag","1");
			
			Map<String,String> existSettingIdMap = new HashMap<String, String>();
			
			if(paymentSettings.size() > 0 && "2".equals(eType)){
			    for (PaymentSetting setting : paymentSettings) {
			    	boolean checkAccountSuccess = false;
			        String appId = setting.getPayAppId();
			        String publicKey = setting.getPublicKey();
			        String privateKey = setting.getPrivateKey();

			        maps.put("appId" , appId);
			        if("1".equals(setting.getPayMode().toString().substring(0,1))){
			            String mchId = setting.getMerchantAccount();
			            String payKey = setting.getPayKey();
			            maps.put("mchId" , mchId);
			            maps.put("payKey" , payKey);
			            
			            //去重
			            String id = appId+"|"+mchId+"|"+payKey;
			            if (existSettingIdMap.containsKey(id)) {
			            	continue;
			            }
			            else {
			            	existSettingIdMap.put(id, "");
			            }

			            //获取微信数据
			            Response res = wechat.getWechatPayment(JSONUtils.toJSONString(maps));
			            
			            if (!"0".equals(res.getResultCode())) {
			                errors.add(appId);
			                checkAccountSuccess = false;
			                logger.error("getWechatPayment结果:"+JsonUtils.toJsonString(res));
			                mapReturn.put("import_message_wechat", res.getResultMessage());
			            }
			            else {
			            	mapReturn.put("import_message_wechat", "处理成功");
			            }
			        }
			        else if("2".equals(setting.getPayMode().toString().substring(0,1))){
			            maps.put("publicKey" , publicKey);
			            maps.put("privateKey" , privateKey);
			            
			            //去重
			            String id = appId+"|"+publicKey+"|"+privateKey;
			            if (existSettingIdMap.containsKey(id)) {
			            	continue;
			            }
			            else {
			            	existSettingIdMap.put(id, "");
			            }

			            //获取支付宝数据
			            Response res = alipay.getAlipayPayment(JSONUtils.toJSONString(maps));
			            
			            if (!"0".equals(res.getResultCode())) {
			                errors.add(appId);
			                checkAccountSuccess = false;
			                logger.error("getAlipayPayment结果:"+JsonUtils.toJsonString(res));
			                mapReturn.put("import_message_alipay", res.getResultMessage());
			            }
			            else {
			            	mapReturn.put("import_message_alipay", "处理成功");
			            }
			        }
			    }

			    //执行对账流程
			    if(errors.size() < paymentSettings.size()){
			        //检查是否执行对账
			        Boolean flag = checkOrgRuleAttribute(orgId);
			        if(flag == true){
			            if(StringUtils.isNotBlank(payMode)){
			                maps.put("payMode", payMode);
			            }
			            
			            JSONObject jsonThird  = thirdPartyfinanceService.checkingThirdfinance(JSONUtils.toJSONString(maps));
			            logger.info("checkingThirdfinance返回值："+JsonUtils.toJsonString(jsonThird));
			            int sourceCount = jsonThird.getIntValue("count");
			            if (jsonThird.getBooleanValue("is_success")) {
			            	logger.info("对账成功!---执行对账成功录入条目：" + sourceCount);
			            	mapReturn.put("check_account_message", "对账成功!---执行对账成功录入条目：" + sourceCount);
			            	response.setResultCodeAndMessage("0", "对账成功!---执行对账成功录入条目：" + sourceCount);
			            	checkAccountFlag = true;
			            }
			            else {
			            	checkAccountFlag = false;
			            	logger.error("对账过程中发生过异常");
			            	logger.error("执行对账成功录入条目：" + sourceCount);
			            	mapReturn.put("check_account_message", "对账过程中发生过异常---执行对账成功录入条目：" + sourceCount);
			            	response.setResultCodeAndMessage("-1", "对账过程中发生过异常---执行对账成功录入条目：" + sourceCount);
			            }
			        }else{
			        	checkAccountFlag = false;
			        	mapReturn.put("check_account_message","该组织：" + orgName + "规则配置不支持对账。");
			            response.setResultCodeAndMessage("5001" , "该组织：" + orgName + "规则配置不支持对账。");
			        }
			        
			       
			        
			        
			    }else{
			    	checkAccountFlag = false;
			        logger.info("拉取第三方对账单出错！错误APPID:" + errors.toString());
			        mapReturn.put("check_account_message","拉取第三方对账单出错！错误APPID:" + errors.toString());
			        response.setResultCodeAndMessage("-1", "拉取第三方对账单出错！错误APPID:" + errors.toString());
			    }

			}else{
			    logger.info("进入特殊对账流程...HIS:" + orgName);
			    List<PaymentSettingResponse> paymentSettingList = new ArrayList<PaymentSettingResponse>();
			    maps.put("org_id" ,orgId);
			    ResponseObject responseObject = paymentService.queryPaymentSettingBySettlementSetting(JSONUtils.toJSONString(maps));
			    
			    if("0".equals(responseObject.getResultCode())){
			        List<SettlementSetting> settings = (List<SettlementSetting>) responseObject.getResultObject();
			        for (SettlementSetting settingVo : settings) {
			        	
			            ResCommon<PaymentSettingResponse> resCommon = PayService.getPayClient().queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(settingVo.getPlatformOrgAppCode(), settingVo.getDevOrgCode(), settingVo.getPayMode());
			            if("0".equals(resCommon.getResultCode())){
			                PaymentSettingResponse setting = resCommon.getResult();
			               
			                String appId = setting.getPayAppId();
			                String publicKey = setting.getPublicKey();
			                String privateKey = setting.getPrivateKey();

			                logger.info(orgName + "准备执行的APPID：" + appId);
			                maps.put("appId" , appId);
			                if("1".equals(setting.getPayMode().toString().substring(0,1))){
			                    String mchId = setting.getMerchantAccount();
			                    String payKey = setting.getPayKey();

			                    maps.put("mchId" , mchId);
			                    maps.put("payKey" , payKey);
			                    
			                    //去重
			                    String id = appId+"|"+mchId+"|"+payKey;
			                    if (existSettingIdMap.containsKey(id)) {//已经拉取过日志
			                    	logger.warn("已经拉取过日志："+id);
			                    	continue;
			                    }
			                    else {
			                    	existSettingIdMap.put(id, "");
			                    }

			                    //获取微信数据
			                    Response res = wechat.getWechatPayment(JSONUtils.toJSONString(maps));
			                    
			                    if (!"0".equals(res.getResultCode())) {
			                    	
			                        errors.add(appId);
			                        logger.error(JsonUtils.toJsonString(res));
			                        getDataFlag = false;
			                    	mapReturn.put("import_message_wechat", res.getResultMessage());
			                    }
			                    else {
			                    	mapReturn.put("import_message_wechat", "处理成功");
			                    }
			                }
			                else if("2".equals(setting.getPayMode().toString().substring(0,1))){

			                	maps.put("publicKey" , publicKey);
			                    maps.put("privateKey" , privateKey);
			                    
			                	 //去重
			                    String id = appId+"|"+publicKey+"|"+privateKey;
			                    if (existSettingIdMap.containsKey(id)) {//已经拉取过日志
			                    	logger.warn("已经拉取过日志："+id);
			                    	continue;
			                    }
			                    else {
			                    	existSettingIdMap.put(id, "");
			                    }
			                    
			                    //获取支付宝数据
			                    Response res = alipay.getAlipayPayment(JSONUtils.toJSONString(maps));
			                    if (!"0".equals(res.getResultCode())) {
			                        errors.add(appId);
			                        logger.error(JsonUtils.toJsonString(res));
			                        getDataFlag = false;
			                        mapReturn.put("import_message_alipay", res.getResultMessage());
			                    }
			                    else {
			                    	mapReturn.put("import_message_alipay", "处理成功");
			                    }
			                }

			                paymentSettingList.add(setting);
			            }
			        } //for
			    } //if 

			    //执行对账流程
			    if(errors.size() < paymentSettingList.size()){
			        //检查是否执行对账
			        Boolean flag = checkOrgRuleAttribute(orgId);
			        if(flag == true){
			            if(StringUtils.isNotBlank(payMode)){
			                maps.put("payMode", payMode);
			            }
			            JSONObject jsonThird  = thirdPartyfinanceService.checkingThirdfinance(JSONUtils.toJSONString(maps));
			            logger.info("checkingThirdfinance返回值："+JsonUtils.toJsonString(jsonThird));
			            int sourceCount = jsonThird.getIntValue("count");
			            if (jsonThird.getBooleanValue("is_success")) {
			            	logger.info("对账成功!---执行对账成功录入条目：" + sourceCount);
			            	mapReturn.put("check_account_message", "对账成功!---执行对账成功录入条目：" + sourceCount);
			            	checkAccountFlag = true;
			            }
			            else {
			            	checkAccountFlag = false;
			            	logger.error("对账过程中发生过异常");
			            	logger.error("执行对账成功录入条目：" + sourceCount);
			            	mapReturn.put("check_account_message", "对账过程中发生过异常---执行对账成功录入条目：" + sourceCount);
			            }
			            
			            
			        }else{
			        	checkAccountFlag = false;
			        	mapReturn.put("check_account_message","该组织：" + orgName + "规则配置不支持对账。");
			        }
			    }else{
			    	checkAccountFlag = false;
			        logger.info("拉取第三方对账单出错！错误APPID:" + errors.toString());
			        mapReturn.put("check_account_message","拉取第三方对账单出错！错误APPID:" + errors.toString());
			    }
			}
		} catch (Exception e) {
			logger.error("platformCheckPaymentByHospital发生异常",e);
			mapReturn.put("total_message", "发生异常"+e.getMessage());
			getDataFlag = false;
			checkAccountFlag = false;
			
		}
        logger.info(JsonUtils.toJsonString(mapReturn));
        String resultCode = "-1";
        String resultMessage = "对账异常";
        if (getDataFlag && checkAccountFlag) {
        	resultCode = "0";
        	resultMessage = "对账成功";
        	//发送成功短信
        	FinanceServiceImpl.sendSmsForSuccess(orgId,"CK_CHECK_SUCESSFUL",orgName, date, YYYYMMDDHHMISS14.format(new Date()),"-","-");
        }
        response = new Response(resultCode,resultMessage,JsonUtils.toJsonString(mapReturn));
        return response;
    }


    /**
     * 根据传入日期数据清理
     *
     * @param datas
     */
    public Response clearCheckPaymentForDatas(String datas) {

        Response response = new Response();
        List<String> files = new ArrayList<String>();
        JSONObject maps = JsonUtils.parseObject(datas);
        String beginPayTime = maps.getString("beginPayTime");
        String endPayTime = maps.getString("endPayTime");
        String payTime = maps.getString("payTime");
        String clearFlag = maps.getString("clearFlag");
        String orgId = maps.getString("orgId");
        
        String dateSms = "";
        try {
        	
            
            if (payTime != null && payTime.length() > 10) {
        		payTime = payTime.substring(0, 10);
        	}
            if (beginPayTime != null && beginPayTime.length() == 10) {
        		beginPayTime = beginPayTime + " 00:00:00";
        	}
        	if (endPayTime != null && endPayTime.length() == 10) {
        		endPayTime = endPayTime + " 23:59:59";
        	}
            //清理第三方对账表数据
            if ("1".equals(clearFlag)) {
                PaymentCheckSourceFile source = new PaymentCheckSourceFile();
                if (StringUtils.isNotBlank(orgId)) {
                    source.setOrgId(orgId);
                }
                if (StringUtils.isNotBlank(payTime)) {
                    source.setBeginPayTime(payTime +" 00:00:00");
                    source.setEndPayTime(payTime + " 23:59:59");
                }else if(StringUtils.isNotBlank(beginPayTime) && StringUtils.isNotBlank(endPayTime)){
                    source.setBeginPayTime(beginPayTime);
                    source.setEndPayTime(endPayTime);
                }

                dateSms = source.getBeginCreatedTime();
                
                List<PaymentCheckSourceFile> sourceFiles = paymentCheckSourceFileDao.select(source);
                if (sourceFiles.size() > 0) {
                    for (PaymentCheckSourceFile file : sourceFiles) {
                        files.add(file.getId());
                    }
                    paymentCheckSourceFileDao.deleteByIds(files);
                }
            }

            PaymentJournal journal = new PaymentJournal();
            //更新流水表状态
            if (StringUtils.isNotBlank(beginPayTime) && StringUtils.isNotBlank(endPayTime)) {
                journal.setBeginPayTime(beginPayTime);
                journal.setEndPayTime(endPayTime);
            } else if (StringUtils.isNotBlank(payTime)) {
                journal.setBeginPayTime(payTime +" 00:00:00");
                journal.setEndPayTime(payTime + " 23:59:59");
            } else {
                response.setResultCodeAndMessage("5003", "对账时间和交易时间不允许同时为null！！");
                return response;
            }
            
            journal.setOrgId(orgId);
            List<PaymentJournal> journals = paymentJournalDao.select(journal);
            if (journals.size() > 0) {
                for (PaymentJournal paymentJournal : journals) {
                    if (paymentJournal.getPayStatus() == 4 || paymentJournal.getPayStatus() == 5) {
                        paymentJournalDao.delete(paymentJournal);
                    } else if (paymentJournal.getPayStatus() == 6) {
                        //根据orderNo查询
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("order_no", paymentJournal.getOrderNo());
                        Response orderRes = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORDER, JSON.toJSONString(map));
                        if ("0".equals(orderRes.getResultCode())) {
                            OrderExtVo vo = JsonUtils.parseObject(orderRes.getResult(), OrderExtVo.class);
                            if (vo.getPayStatus() == 3) {
                                paymentJournal.setPayStatus((short) 1);
                            } else if (vo.getPayStatus() == 7||vo.getPayStatus()==8) {
                                journal.setOrderNo(paymentJournal.getOrderNo());
                                List<PaymentJournal> payJs = paymentJournalDao.select(journal);
                                if(payJs.size() > 1){
                                    Date date = null;
                                    int count = 0;
                                    for (int i = 0; i < payJs.size(); i++) {
                                        Date exPayTime = format.parse(payJs.get(i).getPayTime());
                                        if(date == null || exPayTime.getTime() < date.getTime()){
                                            date = exPayTime;
                                            count = i;
                                        }
                                    }

                                    paymentJournal = payJs.get(count);
                                    paymentJournal.setPayStatus((short) 1);
                                    
                                    payJs.remove(count);
                                    for (PaymentJournal payJ : payJs) {
                                        payJ.setCheckStatus((short) 0);
                                        payJ.setSettlementStatus((short) 0);
                                        payJ.setPayStatus((short) 2);
                                        paymentJournalDao.update(payJ);
                                    }

                                }else{
                                    paymentJournal.setPayStatus((short) 2);
                                }
                            } else {
                                logger.info("order订单不存在！！" + vo.getOrderNo());
                                response.setResultCodeAndMessage("5003", "订单：" + vo.getOrderNo() + " - " + "pay_status 错误！！：" + vo.getPayStatus());
                                throw new RuntimeException("order订单:"+ vo.getOrderNo() +"不存在！！");
                            }
                            paymentJournal.setCheckStatus((short) 0);
                            paymentJournal.setSettlementStatus((short) 0);
                            paymentJournalDao.updateClear(paymentJournal);
                        } else {
                            logger.info("查询失败order订单不存在！！" + paymentJournal.getOrderNo());
                            response.setResultCodeAndMessage("5003", "order订单不存在！！" + paymentJournal.getOrderNo());
                            throw new RuntimeException("order订单不存在！！" + paymentJournal.getOrderNo());
                        }
                    } else {
                        paymentJournal.setCheckStatus((short) 0);
                        paymentJournal.setSettlementStatus((short) 0);
                        paymentJournalDao.updateClear(paymentJournal);
                    }
                }

                response.setResultCodeAndMessage("0", "数据清理成功！");
            } else {
            	logger.info("没有流水数据，无需清理");
//                response.setResultCodeAndMessage("5003", "流水数据为null！！");
            }
        } catch (ParseException e) {
            logger.error("[CheckPaymentServiceImpl.clearCheckPaymentForDatas]" , e);
            
            Map<String,Object> paramOrg = new HashMap<>();
            paramOrg.put("id", orgId);
            JSONObject jsonOrg = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.org.by.id.find", JsonUtils.toJsonString(paramOrg)).getResult());
            String orgName = "";
            if (jsonOrg != null) {
            	orgName = jsonOrg.getString("org_name");
            }
            
            Map<String,Object> paramEvent = new HashMap<>();
        	paramEvent.put("event_code", "CK_PULL_PAY_BILL");
        	paramEvent.put("module_code", "CHECK_ACCOUNT");
        	Response responseEvent = BaseService.callHumpFromInternal("yyt.base.event.get", JsonUtils.toJsonString(paramEvent));
        	
        	if (StringUtils.isNotBlank(responseEvent.getResult())) {
        		EventVo event = JsonUtils.parseObject(responseEvent.getResult(), EventVo.class);
        		FinanceServiceImpl.sendSmsForFail(orgId,"CK_PULL_PAY_BILL", orgName, dateSms.substring(0, 10), YYYYMMDDHHMISS14.format(new Date()),event.getEventLevel()+"","平台数据清理失败");
        	}
        	else {
        		logger.error("获取系统事件定义事事件，无法获取事件级别：CK_PULL_PAY_BILL");
        		FinanceServiceImpl.sendSmsForFail(orgId,"CK_PULL_PAY_BILL",orgName, dateSms.substring(0, 10), YYYYMMDDHHMISS14.format(new Date()),"-1","平台数据清理失败");
        	}
        }

        return response;
    }


    /**
     * 根据orgId查询组织规则配置
     * @param orgId
     * @return
     */
    public Boolean checkOrgRuleAttribute(String orgId){
        Boolean flag = false;
        Response response = new Response();
        Map<String, Object> map = new HashMap<>();
        Org org = new Org();

        response = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORG_BY_ID, JsonUtils.toJsonString(orgId));
        if("0".equals(response.getResultCode())){
            org = JsonUtils.parseObject(response.getResult(), Org.class);
            map.put("attribute_name" , "CheckAccountFlag");
            map.put("org_code" , org.getOrgCode());
            response = BaseService.callHumpFromInternal("yyt.base.rule.select", JSON.toJSONString(map));
            if(StringUtils.isNotBlank(response.getResult())){
                flag = true;
            }
        }else{
            logger.info("checkOrgRuleAttribute.Error!_orgId:" + orgId + ",Error.message:" + response.getResultMessage());
        }

        logger.info("checkOrgRuleAttribute.info_orgId:" + orgId + ",orgCode:" + org.getOrgCode());
        return  flag;
    }



    /**
     * 根据指定条件查找第三方数据
     * @interfaceName yyt.pay.check.payment.get
     */
    public Response getCheckPayment(String datas){
        Response response = new Response();
        PaymentCheckSourceFile source = JsonUtils.parseObject(datas, PaymentCheckSourceFile.class);
        List<PaymentCheckSourceFile> select = paymentCheckSourceFileDao.select(source);
        if(select.size() > 0){
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(select));
        }else{
            response.setResultCodeAndMessage(Response.FAILURE_CODE , Response.FAILURE_MESSAGE);
        }
        return  response;
    }



    /**
     * 更新第三方账单表数据
     * @interfaceName yyt.pay.check.payment.update
     */
    public Response updateCheckPayment(String datas){
        Response response = new Response();
        List<PaymentCheckSourceFile> sources = JSONArray.parseArray(datas, PaymentCheckSourceFile.class);
        try {
            for (PaymentCheckSourceFile source : sources) {
                paymentCheckSourceFileDao.update(source);
            }
            response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);
        } catch (Exception e) {
            logger.error("[CheckPaymentServiceImpl.updateCheckPayment]" , e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE , Response.FAILURE_MESSAGE);
        }

        return  response;
    }


    /**
     * 新增异常订单表数据
     * @interfaceName yyt.pay.check.payment.to.exception.add
     */
    public Response addCheckPaymentToException(String datas){
        Response response = new Response();
        List<OrderCheckedException> exces = JSONArray.parseArray(datas, OrderCheckedException.class);
        try {
            if(exces.size() > 0){
                orderCheckedExceptionDao.batchInsert(exces);
                response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);
            }
        } catch (Exception e) {
            logger.error("[CheckPaymentServiceImpl.addCheckPaymentToException]" , e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE , Response.FAILURE_MESSAGE);
        }

        return  response;
    }


	/**
	 * 对账失败错误短信发送
	 * @interfaceName yyt.pay.check.payment.failsms.send
	 */
	public Response sendCheckPaymentFailsms(String datas){
		Response response = new Response();
		Map<String, String> maps = JsonUtils.parseObject(datas, Map.class);
		String orgId = maps.get("orgId");
		String eventCode = maps.get("eventCode");
		String hospitalName = maps.get("hospitalName");
		String date = maps.get("date");
		String batch = maps.get("batch");
		String level = maps.get("level");
		String problemDescription = maps.get("problemDescription");

		List<ResponseObject> list = financeService.sendSmsForFail(orgId, eventCode, hospitalName, date, batch, level, problemDescription);

		if(list.size() > 0){
			response.setResultCodeAndMessage(Response.SUCCESS_CODE,Response.SUCCESS_MESSAGE);
		}

		return  response;
	}



	/**
	 * 对账失败错误日志记录
	 * @interfaceName yyt.pay.check.payment.faillog.input
	 */
	public Response inputCheckPaymentFaillog(String datas){
		Response response = new Response();
		Map<String, String> maps = JsonUtils.parseObject(datas, Map.class);
		String orgId = maps.get("orgId");
		String eventCode = maps.get("eventCode");
		String errorMessage = maps.get("errorMessage");
		financeService.insertLog(orgId,eventCode,JsonUtils.toJsonString(errorMessage));
		response.setResultCodeAndMessage(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE);
		return  response;
	}



    public static void main(String[] args) throws Exception{
//        List<String> v1 = new ArrayList<String>();
//
//        v1.add("2017-02-24 14:59:54");
//        v1.add("2017-02-21 14:59:54");
//        v1.add("2017-02-23 14:59:54");
//        v1.add("2017-02-20 14:59:54");
//        v1.add("2017-02-25 14:59:54");
//        v1.add("2017-02-21 12:59:54");
//        v1.add("2017-02-26 12:59:54");
//
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = null;
//        int count = 0;
//        for (int i = 0; i < v1.size(); i++) {
//            Date date1 = format.parse(v1.get(i));
//            if(date == null || date1.getTime() < date.getTime()){
//                date = date1;
//                count = i;
//            }
//        }
//
//        System.out.println(format.format(date));
//        System.out.println(v1.get(count));
//        long sub = getDaySub("2017-02-25", "2017-02-26");


    }
}
